package com.studyyoun.android.nonghe.msg.item;
/**
 * Created by zhaolong on 2017/10/11.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.androidlongs.pullrefreshrecyclerylib.common.FullyLinearLayoutManager;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.androidcommonbaselibrary.view.DropDownSpringbackScrollView;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.msg.activity.MsgDetaileActivity;
import com.studyyoun.android.nonghe.msg.model.MsgCommentModel;
import com.studyyoun.android.nonghe.msg.model.MsgModel;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;
import com.studyyoun.android.nonghe.welcom.model.UserModel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * class infation
 * 评论相关
 */
public class ItemMsgDetaileRecommentShareClass {
    private Context mContext;
    private Handler mHandler;
    private MsgModel mArtModel;
    private PopupWindow mRecommentPopupWindow;
    private final TextView mNoArtCommentDataTextView;
    private final RecyclerView mArtCommentDataRecyclerView;
    private final TextView mArtRecommentCountTextView;

    private int mCurrentScrollLocation = 1;
    private int mCurrentBottomType =-1;
    private ObjectAnimator mObjectAnimator;

    public ItemMsgDetaileRecommentShareClass(MsgDetaileActivity context, Handler handler, MsgModel artModel) {
        mContext = context;
        mHandler = handler;
        mArtModel = artModel;

        FrameLayout reCommentFramelayout = context.findViewById(R.id.fl_recomment);
        LinearLayout reCommentLinearLayout = context.findViewById(R.id.ll_recomment);
        final LinearLayout artBottomLayout = context.findViewById(R.id.ll_art_bottom_layout);

        final DropDownSpringbackScrollView springbackScrollView = context.findViewById(R.id.ddsv_main_msg_content);


        reCommentLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showRecommentPopupWindow(view);
            }
        });


        springbackScrollView.setOnCustomScrollChangeLisernet(new DropDownSpringbackScrollView.OnCustomScrollChangeLisernet() {
            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {
                LogUtils.d("l "+l+"  "+t+" -- ol "+oldl+"  "+oldt);
                int flagTop = t-oldt;
                if (flagTop>0){
                    if (mCurrentBottomType!=1) {
                        mCurrentBottomType=1;
                        if (mObjectAnimator != null) {
                            if (mObjectAnimator.isRunning()) {
                                mObjectAnimator.cancel();
                            }
                        }
                        mObjectAnimator = ObjectAnimator.ofFloat(artBottomLayout,"translationY",artBottomLayout.getHeight());
                        mObjectAnimator.setDuration(200);

                        mObjectAnimator.setInterpolator(new LinearInterpolator());
                        mObjectAnimator.start();
                    }

                }else {
                    if (mCurrentBottomType==1) {
                        mCurrentBottomType=-1;

                        if (mObjectAnimator != null) {
                            if (mObjectAnimator.isRunning()) {
                                mObjectAnimator.cancel();
                            }
                        }
                        //向上
                        mObjectAnimator = ObjectAnimator.ofFloat(artBottomLayout, "translationY", 0);
                        mObjectAnimator.setDuration(200);
                        mObjectAnimator.setInterpolator(new LinearInterpolator());
                        mObjectAnimator.start();
                    }
                }
            }
        });


        mNoArtCommentDataTextView = context.findViewById(R.id.tv_art_comment_no_data);

        mArtCommentDataRecyclerView = context.findViewById(R.id.rv_art_comment_list);
        mArtCommentDataRecyclerView.setLayoutManager(new FullyLinearLayoutManager(mContext));
        mArtCommentDataRecyclerView.setAdapter(mArtCommentViewHolderAdapter);

        mArtRecommentCountTextView = context.findViewById(R.id.tv_art_comment_list_size);
    }

    /**
     * 显示回复评论
     *
     * @param view
     */
    private void showRecommentPopupWindow(View view) {
        if (mRecommentPopupWindow != null) {
            mRecommentPopupWindow.dismiss();
            mRecommentPopupWindow = null;
            return;
        }
        // 获取自定义布局文件activity_popupwindow_left.xml的视图
        View popupWindow_view = View.inflate(view.getContext(), R.layout.pop_art_recomment_layout, null);

        // 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
        mRecommentPopupWindow = new PopupWindow(popupWindow_view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        //焦点设置
        mRecommentPopupWindow.setFocusable(true);
        //设置点击背景不消失
        mRecommentPopupWindow.setOutsideTouchable(true);
        mRecommentPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        // 设置透明背景
        mRecommentPopupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        //设置动画

        mRecommentPopupWindow.setAnimationStyle(com.studyyoun.android.androidcommonbaselibrary.R.style.popwin_from_bottom_anim_style);

        mRecommentPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        //显示
        mRecommentPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);


        TextView cancleShareTextView = popupWindow_view.findViewById(R.id.tv_cancle_share);
        cancleShareTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeSharePop();
            }
        });

        final EditText artRecommentEditText = popupWindow_view.findViewById(R.id.et_art_recomment_input);
        TextView commitCommentTextView = popupWindow_view.findViewById(R.id.tv_commit_share);
        commitCommentTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String input = artRecommentEditText.getText().toString();
                if (TextUtils.isEmpty(input)) {
                    ToastUtils.show("请输入评论内容", mContext);
                } else {
                    closeSharePop();
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            LogUtils.d("提交评论 ");
                            commitCommentContentFunction(input);
                        }
                    }, 300);
                }
            }
        });

        LinearLayout backgrouncLayout = popupWindow_view.findViewById(R.id.ll_recomment_background_other);
        backgrouncLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeSharePop();
            }
        });
    }


    /**
     * 提交评论
     *
     * @param input
     */
    private void commitCommentContentFunction(String input) {

        String url = HttpUrlHelper.commitMsgRecommentUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("userId", CommonUserHelper.getUserModel().getUserId() + "");
        key.put("msgId", mArtModel.getId() + "");
        key.put("commentContent", input);
        key.put("parent", "root");

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                ToastUtils.show("提交评论成功", mContext);

                //重新加载评论信息
                loadingMsgRecomment(mArtModel);
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("服务异常:提交评论失败", mContext);
            }
        });
    }


    private List<MsgCommentModel> mArtCommentResponseModelList = new ArrayList<>();
    /**
     * 加载评论
     * @param artModel
     */
    public void loadingMsgRecomment(MsgModel artModel) {
        mArtModel = artModel;
        String url = HttpUrlHelper.getMsgRecommentUrl;
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("msgId", mArtModel.getId() + "");

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(MsgCommentModel.class) {
            @Override
            public void onSuccess(Object obj) {
                List<MsgCommentModel> artCommentResponseModelList = (List<MsgCommentModel>) obj;
                LogUtils.d(" 加载评论成功 artCommentResponseModelList size is  "+artCommentResponseModelList.size());
                mArtCommentResponseModelList.clear();
                mArtCommentResponseModelList.addAll(artCommentResponseModelList);

                if (mArtCommentResponseModelList.size()>0){
                    mNoArtCommentDataTextView.setVisibility(View.GONE);
                    mArtRecommentCountTextView.setText(""+mArtCommentResponseModelList.size());
                    setArtCommentDataFunction();
                }else {
                    mNoArtCommentDataTextView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFaile(Object obj) {
                mNoArtCommentDataTextView.setVisibility(View.VISIBLE);
                LogUtils.e("服务异常:加载评论失败");
            }
        });
    }

    private void setArtCommentDataFunction() {
        mArtCommentViewHolderAdapter.notifyDataSetChanged();
    }

    private RecyclerView.Adapter<RecyclerView.ViewHolder> mArtCommentViewHolderAdapter = new RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(mContext,R.layout.item_art_comment_layout,null);
            return new ArtCommentViewHolder(view);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            ArtCommentViewHolder viewHolder = (ArtCommentViewHolder) holder;

            MsgCommentModel artCommentModel = mArtCommentResponseModelList.get(position);
            viewHolder.setDatasFunction(artCommentModel,position);

        }

        @Override
        public int getItemCount() {
            return mArtCommentResponseModelList.size();
        }


    };

    private static  class  ArtCommentViewHolder extends RecyclerView.ViewHolder{

        private final TextView mUserTitleTextView;
        private final CircleImageView mUerTitleImageView;
        private final TextView mArtCommentContentTextView;
        private final TextView mArtCommentTimeTextView;
        private final TextView mArtCommentCountTextView;

        public ArtCommentViewHolder(View itemView) {
            super(itemView);
            mUserTitleTextView = itemView.findViewById(R.id.tv_recomment_user_title);
            mUerTitleImageView = itemView.findViewById(R.id.tv_recomment_user_img);

            mArtCommentContentTextView = itemView.findViewById(R.id.tv_recomment_content);

            mArtCommentTimeTextView = itemView.findViewById(R.id.tv_recomment_time);

            mArtCommentCountTextView = itemView.findViewById(R.id.tv_recomment_user_count);


        }

        public void setDatasFunction(MsgCommentModel artCommentResponseModel, int position) {
            UserModel userModel = artCommentResponseModel.getUserModel();

            if (userModel != null) {
                mUserTitleTextView.setText(userModel.getNixe());
                String imageUrl = HttpUrlHelper.BaseImageHost+userModel.getImgUrl();
                CommonGlideUtils.showImageView(itemView.getContext(),R.mipmap.default_title,imageUrl,mUerTitleImageView);
            }else {
                mUserTitleTextView.setText("***");
                mUerTitleImageView.setImageDrawable(itemView.getContext().getResources().getDrawable(R.mipmap.default_title));
            }

            mArtCommentCountTextView.setText((position+1)+"楼");
            mArtCommentContentTextView.setText(artCommentResponseModel.getCommentContent());

            mArtCommentTimeTextView.setText(artCommentResponseModel.getFormateTime());

        }
    }



    private void closeSharePop() {
        if (mRecommentPopupWindow != null) {
            mRecommentPopupWindow.dismiss();
            mRecommentPopupWindow = null;
        }
    }
}
